package com.chinalwb.are.demo.slice;

import com.chinalwb.are.ListStateBean;
import com.chinalwb.are.demo.DemoUtil;
import com.chinalwb.are.demo.ResourceTable;

import com.chinalwb.are.styles.ListComponent;
import com.chinalwb.are.utils.*;
import com.chinalwb.are.view.ColorPickerDialog;
import com.chinalwb.are.view.RichTextView;
import com.chinalwb.are.view.SelectFontSizeDialog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.ScrollView;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.utils.Rect;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.HashMap;
import java.util.Optional;

/**
 * ARE_MultiInstanceSlice
 *
 * @since 2021/06/22
 */
public class ARE_MultiInstanceSlice extends AbilitySlice {
    private static final int TYPE_O = 1;
    private static final int TYPE_T = 2;
    private static final int TYPE_E = 3;
    private static final int TYPE_F = 4;
    private ListComponent listOne;
    private ListComponent listTwo;
    private ListComponent listThree;
    private ListComponent listFour;
    private String colorOne = "#000000";
    private String colorTwo = "#000000";
    private String colorThree = "#000000";
    private String colorFour = "#000000";
    private int textSizeOne = 18;
    private int textSizeTwo = 18;
    private int textSizeThree = 18;
    private int textSizeFour = 18;
    private final HashMap<Integer, Boolean> styleMapOne = new HashMap<>();
    private final HashMap<Integer, Boolean> styleMapTwo = new HashMap<>();
    private final HashMap<Integer, Boolean> styleMapThree = new HashMap<>();
    private final HashMap<Integer, Boolean> styleMapFour = new HashMap<>();
    private TextDecorator textDecoratorOne;
    private TextDecorator textDecoratorTwo;
    private TextDecorator textDecoratorThree;

    private EventHandler mainHandler = new EventHandler(EventRunner.getMainEventRunner());
    private MyTask myTask = null;
    class MyTask implements Runnable {
        private final int softHeight;
        private final ScrollView root;
        private final Rect decorRect;

        public MyTask(int softHeight, ScrollView root, Rect decorRect) {
            this.softHeight = softHeight;
            this.root = root;
            this.decorRect = decorRect;
        }

        @Override
        public void run() {
            Component focusView = root.findFocus();
            int focusTop = focusView.getLocationOnScreen()[1];// 焦点控件的左上角
            root.fluentScrollByY(focusTop + focusView.getHeight() - decorRect.top - decorRect.getHeight()+ AttrHelper.vp2px(50,getContext()));
        }
    }


    @Override
    protected void onStart(Intent intent) {
        DemoUtil.initStatus(getAbility());
        getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_multiple);
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(getContext());
        Point pt = new Point();
        display.get().getSize(pt);
        int screenHeight = pt.getPointYToInt();// 不包括状态栏(手机时间、wifi显示的那一部分，) 2211，状态栏是129，加起来就是2340

        ScrollView root = (ScrollView) findComponentById(ResourceTable.Id_scroll);
        root.setLayoutRefreshedListener(new Component.LayoutRefreshedListener() {
            @Override
            public void onRefreshed(Component component) {
                // 包括标题栏，但不包括状态栏。默认 大小 (0,129,1080,2340),top=129即状态栏 , height=2211。 同android的decorView
                Rect decorRect = new Rect();
                component.getWindowVisibleRect(decorRect);
                if (decorRect.getHeight() == 0) {
                    // 刚进入界面可能为0
                    return;
                }
                int softHeight = screenHeight - decorRect.getHeight();

                if (softHeight > 100) {// 当输入法高度大于100判定为输入法打开了
                    if (myTask != null) {
                        mainHandler.removeTask(myTask);
                        myTask = null;
                    }
                    mainHandler.postTask(myTask = new MyTask(softHeight, root, decorRect), 100);
                }
            }
        });

        listOne = FindUtils.findListComponentById(getAbility(), ResourceTable.Id_list_one);
        listTwo = FindUtils.findListComponentById(getAbility(), ResourceTable.Id_list_two);
        listThree = FindUtils.findListComponentById(getAbility(), ResourceTable.Id_list_three);
        listFour = FindUtils.findListComponentById(getAbility(), ResourceTable.Id_list_four);
        RichTextView tvContentOne = FindUtils.findRichTextById(getAbility(), ResourceTable.Id_tv_content_one);
        CursorTextField cursorTextOne = FindUtils.findCursorTextFieldById(
                getAbility(), ResourceTable.Id_cursor_text_one);
        textDecoratorOne = new TextDecorator();
        textDecoratorOne.init(cursorTextOne, tvContentOne);
        textDecoratorTwo = new TextDecorator();
        RichTextView tvContentTwo = FindUtils.findRichTextById(
                getAbility(), ResourceTable.Id_tv_content_two);
        CursorTextField cursorTextTwo = FindUtils.findCursorTextFieldById(
                getAbility(), ResourceTable.Id_cursor_text_two);
        textDecoratorTwo.init(cursorTextTwo, tvContentTwo);
        textDecoratorThree = new TextDecorator();
        RichTextView tvContentThree = FindUtils.findRichTextById(
                getAbility(), ResourceTable.Id_tv_content_three);
        CursorTextField cursorTextThree = FindUtils.findCursorTextFieldById(
                getAbility(), ResourceTable.Id_cursor_text_three);
        textDecoratorThree.init(cursorTextThree, tvContentThree);
        TextDecorator textDecoratorFour = new TextDecorator();
        RichTextView tvContentFour = FindUtils.findRichTextById(
                getAbility(), ResourceTable.Id_tv_content_four);
        CursorTextField cursorTextFour = FindUtils.findCursorTextFieldById(
                getAbility(), ResourceTable.Id_cursor_text_four);
        textDecoratorFour.init(cursorTextFour, tvContentFour);
        initList();
        listOne.setOnItemClickListener((listStateBean, position) ->
                itemClick(TYPE_O, listStateBean, position, styleMapOne, textDecoratorOne));

        listTwo.setOnItemClickListener((listStateBean, position) ->
                itemClick(TYPE_T, listStateBean, position, styleMapTwo, textDecoratorTwo));

        listThree.setOnItemClickListener((listStateBean, position) ->
                itemClick(TYPE_E, listStateBean, position, styleMapThree, textDecoratorThree));

        listFour.setOnItemClickListener((listStateBean, position) ->
                itemClick(TYPE_F, listStateBean, position, styleMapFour, TextDecorator.getInstance()));
    }


    private void initList() {
        Integer[] icon = {
                com.chinalwb.are.ResourceTable.Media_fontsize,
                com.chinalwb.are.ResourceTable.Media_bold,
                com.chinalwb.are.ResourceTable.Media_italic,
                com.chinalwb.are.ResourceTable.Media_underline,
                com.chinalwb.are.ResourceTable.Media_strikethrough,
                com.chinalwb.are.ResourceTable.Media_hr,
                com.chinalwb.are.ResourceTable.Media_subscript,
                com.chinalwb.are.ResourceTable.Media_superscript,
                com.chinalwb.are.ResourceTable.Media_quote,
                com.chinalwb.are.ResourceTable.Media_foregroundcolor,
                com.chinalwb.are.ResourceTable.Media_background,
                com.chinalwb.are.ResourceTable.Media_link,
                com.chinalwb.are.ResourceTable.Media_listnumber,
                com.chinalwb.are.ResourceTable.Media_listbullet,
                com.chinalwb.are.ResourceTable.Media_alignleft,
                com.chinalwb.are.ResourceTable.Media_aligncenter,
                com.chinalwb.are.ResourceTable.Media_alignright,
                com.chinalwb.are.ResourceTable.Media_image,
                com.chinalwb.are.ResourceTable.Media_video,
        };
        listOne.setData(getContext(), ListUtils.getList(icon, 0, 9));
        listTwo.setData(getContext(), ListUtils.getList(icon, 0, 9));
        listThree.setData(getContext(), ListUtils.getList(icon, 0, 9));
        listFour.setData(getContext(), ListUtils.getList(icon, 0, 9));
    }

    private void setStyle(ListStateBean listStateBean, int style, StateBean stateBean, HashMap<Integer, Boolean> tempMap, HashMap<Integer, Boolean> styleMap) {
        if (listStateBean.getIsSelected()) {
            styleMap.put(style, true);
        } else {
            styleMap.remove(style);
        }
        tempMap.putAll(styleMap);
        stateBean.setStyleMap(tempMap);
    }

    private void itemClick(int type, ListStateBean listStateBean, int position, HashMap<Integer, Boolean> map, TextDecorator textDecorator) {
        StateBean stateBean = new StateBean();
        HashMap<Integer, Boolean> tempMap = new HashMap<>();
        switch (position) {
            case 0:
                // 字体大小
                setTextSize(type, tempMap, stateBean, map, textDecorator);
                break;
            case 1:
                // 粗体
                setStyle(listStateBean, TextDecorator.TYPE_BOLD, stateBean, tempMap, map);
                textDecorator.setStateBean(stateBean);
                break;
            case 2:
                // 斜体
                setStyle(listStateBean, TextDecorator.TYPE_ITALIC, stateBean, tempMap, map);
                textDecorator.setStateBean(stateBean);
                break;
            case 3:
                // 下划线
                setStyle(listStateBean, TextDecorator.UNDERLINE, stateBean, tempMap, map);
                textDecorator.setStateBean(stateBean);
                break;
            case 4:
                // 中划线
                setStyle(listStateBean, TextDecorator.STRIKETHROUGH, stateBean, tempMap, map);
                textDecorator.setStateBean(stateBean);
                break;
            case 6:
                // 下标
                setStyle(listStateBean, TextDecorator.SUBSCRIPT, stateBean, tempMap, map);
                textDecorator.setStateBean(stateBean);
                break;
            case 7:
                // 上标
                setStyle(listStateBean, TextDecorator.SUPERSCRIPT, stateBean, tempMap, map);
                textDecorator.setStateBean(stateBean);
                break;
            case 9:
                // 颜色
                setTextColor(type, stateBean, map, textDecorator);
                break;
            case 10:
                // 背景
                setStyle(listStateBean, TextDecorator.TEXT_BAG, stateBean, tempMap, map);
                stateBean.setBgColor(listStateBean.getIsSelected() ?
                        Color.YELLOW.getValue() : Color.TRANSPARENT.getValue());
                textDecorator.setStateBean(stateBean);
                break;
            default:
                new ToastDialog(getContext()).setText("暂不支持此功能").show();
                break;
        }
    }

    private void setTextSize(int type, HashMap<Integer, Boolean> tempMap, StateBean stateBean, HashMap<Integer, Boolean> map, TextDecorator textDecorator) {
        SelectFontSizeDialog selectFontSizeDialog = new SelectFontSizeDialog(getContext(), getListComponent(type), getIntComponent(type));
        selectFontSizeDialog.show();
        selectFontSizeDialog.setSelectColorListener(size -> {
            setIntComponent(type, size);
            map.put(TextDecorator.ABSOLUTE_SIZE, true);
            tempMap.putAll(map);
            stateBean.setSize(size);
            stateBean.setStyleMap(tempMap);
            textDecorator.setStateBean(stateBean);
        });
    }

    private void setTextColor(int type, StateBean stateBean, HashMap<Integer, Boolean> map, TextDecorator textDecorator) {
        ColorPickerDialog colorPickerDialog = new ColorPickerDialog(getContext(), getListComponent(type), getStringComponent(type));
        colorPickerDialog.show();
        colorPickerDialog.setSelectColorListener(colors -> {
            setStringComponent(type, colors);
            map.put(TextDecorator.TEXT_COLOR, true);
            stateBean.setColor(Color.getIntColor(colorFour));
            stateBean.setStyleMap(styleMapFour);
            textDecorator.setStateBean(stateBean);
        });
    }

    /**
     * 获取ListComponent
     *
     * @param type type
     * @return ListComponent
     */
    private ListComponent getListComponent(int type) {
        switch (type) {
            case TYPE_O:
                return listOne;
            case TYPE_T:
                return listTwo;
            case TYPE_E:
                return listThree;
            case TYPE_F:
                return listFour;
            default:
                break;
        }
        return new ListComponent(getContext());
    }

    /**
     * 获取int
     *
     * @param type type
     * @return int
     */
    private int getIntComponent(int type) {
        switch (type) {
            case TYPE_O:
                return textSizeOne;
            case TYPE_T:
                return textSizeTwo;
            case TYPE_E:
                return textSizeThree;
            case TYPE_F:
                return textSizeFour;
            default:
                break;
        }
        return 0;
    }

    /**
     * 获取int
     *
     * @param type type
     * @param size size
     */
    private void setIntComponent(int type, int size) {
        switch (type) {
            case TYPE_O:
                textSizeOne = size;
                break;
            case TYPE_T:
                textSizeTwo = size;
                break;
            case TYPE_E:
                textSizeThree = size;
                break;
            case TYPE_F:
                textSizeFour = size;
                break;
            default:
                break;
        }
    }

    /**
     * 获取String
     *
     * @param type type
     * @return String
     */
    private String getStringComponent(int type) {
        switch (type) {
            case TYPE_O:
                return colorOne;
            case TYPE_T:
                return colorTwo;
            case TYPE_E:
                return colorThree;
            case TYPE_F:
                return colorFour;
            default:
                break;
        }
        return "";
    }

    /**
     * 获取String
     *
     * @param type  type
     * @param color color
     */
    private void setStringComponent(int type, String color) {
        switch (type) {
            case TYPE_O:
                colorOne = color;
                break;
            case TYPE_T:
                colorTwo = color;
                break;
            case TYPE_E:
                colorThree = color;
                break;
            case TYPE_F:
                colorFour = color;
                break;
            default:
                break;
        }
    }
}
